<template>
  <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    @load="onLoad"
  >
    <van-cell
      v-for="(item, index) in results"
      :key="index"
      :title="item.title"
    />
  </van-list>
</template>

<script>
import { getSearchResultAPI } from '@/api'
export default {
  props: {
    keywords: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      results: [],
      loading: false,
      finished: false,
      page: 1,
      per_page: 10
    }
  },
  watch: {
    // 先创建的同时传值  watch刚开始会监听不到   需要进入页面立即调用请求
    keywords: {
      immediate: true,
      handler() {
        this.getSearchResult()
      }
    }
  },
  methods: {
    async getSearchResult() {
      try {
        const { data } = await getSearchResultAPI({
          q: this.keywords
        })
        // console.log(data)
        this.results = data.data.results
      } catch (error) {
        console.log(error)
        this.$toast.fail('加载失败，请刷新')
      }
    },
    async onLoad() {
      this.page++
      try {
        const { data } = await getSearchResultAPI({
          q: this.keywords,
          page: this.page,
          per_page: this.per_page
        })
        // 判断结果是否全部展示完毕
        if (
          (data.data.result && data.data.result.length) ||
          data.data.total_count <= (this.page - 1) * this.per_page
        ) {
          this.finished = true
          return
        }
        // 添加新的返回结果
        this.results = [...this.results, ...data.data.results]
      } catch (error) {
        this.$toast.fail('获取搜索结果失败，请刷新')
        console.log(error)
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style></style>
